package cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.crossborder.platform.controller.admin.platformapiconfig.vo.PlatformApiConfigSaveReqVO;
import cn.iocoder.yudao.module.crossborder.platform.controller.admin.platformconfig.vo.PlatformConfigSaveReqVO;
import cn.iocoder.yudao.module.crossborder.platform.controller.admin.platformfeeconfig.vo.PlatformFeeConfigSaveReqVO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformapiconfig.PlatformApiConfigDO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformconfig.PlatformConfigDO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformfeeconfig.PlatformFeeConfigDO;
import cn.iocoder.yudao.module.crossborder.platform.service.platformapiconfig.PlatformApiConfigService;
import cn.iocoder.yudao.module.crossborder.platform.service.platformconfig.PlatformConfigService;
import cn.iocoder.yudao.module.crossborder.platform.service.platformfeeconfig.PlatformFeeConfigService;
import cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.config.AmazonPlatformConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Amazon配置管理服务
 * 负责Amazon平台的各种配置管理，包括API配置、费率配置、同步配置等
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class AmazonConfigManagementService {

    @Resource
    private PlatformConfigService platformConfigService;
    
    @Resource
    private PlatformApiConfigService platformApiConfigService;
    
    @Resource
    private PlatformFeeConfigService platformFeeConfigService;
    
    @Resource
    private AmazonPlatformConfig amazonPlatformConfig;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // Amazon平台相关常量
    private static final String AMAZON_PLATFORM_CODE = "amazon";
    private static final String AMAZON_PLATFORM_NAME = "Amazon";
    private static final Long AMAZON_PLATFORM_ID = 1L;

    /**
     * 初始化Amazon配置
     */
    @PostConstruct
    public void initializeAmazonConfigs() {
        log.info("开始初始化Amazon配置管理");

        try {
            // 注意：忽略自动多租户，因为要全局初始化配置
            TenantUtils.executeIgnore(() -> {
                // 1. 初始化平台基础配置
                initializePlatformConfig();

                // 2. 初始化API配置
                initializeApiConfigs();

                // 3. 初始化费率配置
                initializeFeeConfigs();
            });

            log.info("Amazon配置管理初始化完成");
        } catch (Exception e) {
            log.error("Amazon配置管理初始化失败", e);
        }
    }

    /**
     * 获取Amazon API配置
     *
     * @param apiType API类型
     * @return API配置
     */
    public Map<String, Object> getApiConfig(String apiType) {
        try {
            List<PlatformApiConfigDO> apiConfigs = platformApiConfigService.getPlatformApiConfigListByPlatformId(AMAZON_PLATFORM_ID);
            
            for (PlatformApiConfigDO config : apiConfigs) {
                if (apiType.equals(config.getApiType())) {
                    Map<String, Object> configMap = new HashMap<>();
                    configMap.put("apiName", config.getApiName());
                    configMap.put("apiEndpoint", config.getApiEndpoint());
                    configMap.put("httpMethod", config.getHttpMethod());
                    configMap.put("requestHeaders", parseJsonConfig(config.getRequestHeaders()));
                    configMap.put("requestParams", parseJsonConfig(config.getRequestParams()));
                    configMap.put("responseMapping", parseJsonConfig(config.getResponseMapping()));
                    configMap.put("rateLimitTps", config.getRateLimitPerMinute());
                    configMap.put("timeout", config.getTimeoutSeconds());
                    return configMap;
                }
            }
            
            return new HashMap<>();
        } catch (Exception e) {
            log.error("获取Amazon API配置失败: apiType={}", apiType, e);
            return new HashMap<>();
        }
    }

    /**
     * 获取Amazon费率配置
     *
     * @param feeType 费率类型
     * @return 费率配置
     */
    public Map<String, Object> getFeeConfig(String feeType) {
        try {
            List<PlatformFeeConfigDO> feeConfigs = platformFeeConfigService.getPlatformFeeConfigListByPlatformId(AMAZON_PLATFORM_ID);
            
            for (PlatformFeeConfigDO config : feeConfigs) {
                if (feeType.equals(config.getFeeType())) {
                    Map<String, Object> configMap = new HashMap<>();
                    configMap.put("feeName", config.getFeeName());
                    configMap.put("feeNameEn", config.getFeeNameEn());
                    configMap.put("calculationMethod", config.getCalculationMethod());
                    configMap.put("feeRate", config.getFeeRate());
                    configMap.put("fixedAmount", config.getFixedAmount());
                    configMap.put("minFee", config.getMinFee());
                    configMap.put("maxFee", config.getMaxFee());
                    configMap.put("currency", config.getCurrency());
                    configMap.put("tierConfig", parseJsonConfig(config.getTierConfig()));
                    return configMap;
                }
            }
            
            return new HashMap<>();
        } catch (Exception e) {
            log.error("获取Amazon费率配置失败: feeType={}", feeType, e);
            return new HashMap<>();
        }
    }

    /**
     * 更新Amazon API配置
     *
     * @param apiType API类型
     * @param configData 配置数据
     * @return 是否成功
     */
    public boolean updateApiConfig(String apiType, Map<String, Object> configData) {
        try {
            List<PlatformApiConfigDO> apiConfigs = platformApiConfigService.getPlatformApiConfigListByPlatformId(AMAZON_PLATFORM_ID);
            
            for (PlatformApiConfigDO config : apiConfigs) {
                if (apiType.equals(config.getApiType())) {
                    PlatformApiConfigSaveReqVO updateReqVO = BeanUtils.toBean(config, PlatformApiConfigSaveReqVO.class);
                    
                    // 更新配置字段
                    if (configData.containsKey("apiEndpoint")) {
                        updateReqVO.setApiEndpoint((String) configData.get("apiEndpoint"));
                    }
                    if (configData.containsKey("requestHeaders")) {
                        updateReqVO.setRequestHeaders(toJsonString(configData.get("requestHeaders")));
                    }
                    if (configData.containsKey("requestParams")) {
                        updateReqVO.setRequestParams(toJsonString(configData.get("requestParams")));
                    }
//                    if (configData.containsKey("rateLimitTps")) {
//                        updateReqVO.setRateLimitTps((Integer) configData.get("rateLimitTps"));
//                    }
                    if (configData.containsKey("timeout")) {
                        updateReqVO.setTimeoutSeconds((Integer) configData.get("timeout"));
                    }
                    
                    platformApiConfigService.updatePlatformApiConfig(updateReqVO);
                    log.info("更新Amazon API配置成功: apiType={}", apiType);
                    return true;
                }
            }
            
            log.warn("未找到对应的Amazon API配置: apiType={}", apiType);
            return false;
        } catch (Exception e) {
            log.error("更新Amazon API配置失败: apiType={}", apiType, e);
            return false;
        }
    }

    /**
     * 更新Amazon费率配置
     *
     * @param feeType 费率类型
     * @param configData 配置数据
     * @return 是否成功
     */
    public boolean updateFeeConfig(String feeType, Map<String, Object> configData) {
        try {
            List<PlatformFeeConfigDO> feeConfigs = platformFeeConfigService.getPlatformFeeConfigListByPlatformId(AMAZON_PLATFORM_ID);
            
            for (PlatformFeeConfigDO config : feeConfigs) {
                if (feeType.equals(config.getFeeType())) {
                    PlatformFeeConfigSaveReqVO updateReqVO = BeanUtils.toBean(config, PlatformFeeConfigSaveReqVO.class);
                    
                    // 更新配置字段
                    if (configData.containsKey("feeRate")) {
                        updateReqVO.setFeeRate((BigDecimal) configData.get("feeRate"));
                    }
                    if (configData.containsKey("fixedAmount")) {
                        updateReqVO.setFixedAmount((BigDecimal) configData.get("fixedAmount"));
                    }
                    if (configData.containsKey("minFee")) {
                        updateReqVO.setMinFee((BigDecimal) configData.get("minFee"));
                    }
                    if (configData.containsKey("maxFee")) {
                        updateReqVO.setMaxFee((BigDecimal) configData.get("maxFee"));
                    }
                    if (configData.containsKey("tierConfig")) {
                        updateReqVO.setTierConfig(toJsonString(configData.get("tierConfig")));
                    }
                    
                    platformFeeConfigService.updatePlatformFeeConfig(updateReqVO);
                    log.info("更新Amazon费率配置成功: feeType={}", feeType);
                    return true;
                }
            }
            
            log.warn("未找到对应的Amazon费率配置: feeType={}", feeType);
            return false;
        } catch (Exception e) {
            log.error("更新Amazon费率配置失败: feeType={}", feeType, e);
            return false;
        }
    }

    /**
     * 获取Amazon同步配置
     *
     * @return 同步配置
     */
    public Map<String, Object> getSyncConfig() {
        return amazonPlatformConfig.getSyncConfig();
    }

    /**
     * 更新Amazon同步配置
     *
     * @param syncConfig 同步配置
     * @return 是否成功
     */
    public boolean updateSyncConfig(Map<String, Object> syncConfig) {
        try {
            PlatformConfigDO config = amazonPlatformConfig.getAmazonConfig();
            if (config == null) {
                log.warn("Amazon平台配置不存在");
                return false;
            }
            
            PlatformConfigSaveReqVO updateReqVO = BeanUtils.toBean(config, PlatformConfigSaveReqVO.class);
            updateReqVO.setSyncConfig(toJsonString(syncConfig));
            
            platformConfigService.updatePlatformConfig(updateReqVO);
            amazonPlatformConfig.refreshCache(); // 刷新缓存
            
            log.info("更新Amazon同步配置成功");
            return true;
        } catch (Exception e) {
            log.error("更新Amazon同步配置失败", e);
            return false;
        }
    }

    /**
     * 获取所有Amazon配置概览
     *
     * @return 配置概览
     */
    public Map<String, Object> getConfigOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        try {
            // 平台基础配置
            PlatformConfigDO platformConfig = amazonPlatformConfig.getAmazonConfig();
            overview.put("platformConfig", platformConfig != null ? 
                new HashMap<String, Object>() {{
                    put("enabled", platformConfig.getEnabled());
                    put("status", platformConfig.getStatus());
                }} : 
                new HashMap<String, Object>() {{
                    put("enabled", false);
                    put("status", 0);
                }});
            
            // API配置统计
            List<PlatformApiConfigDO> apiConfigs = platformApiConfigService.getPlatformApiConfigListByPlatformId(AMAZON_PLATFORM_ID);
            overview.put("apiConfigCount", apiConfigs.size());
            overview.put("enabledApiCount", apiConfigs.stream().mapToInt(c -> Boolean.TRUE.equals(c.getEnabled()) ? 1 : 0).sum());

            // 费率配置统计
            List<PlatformFeeConfigDO> feeConfigs = platformFeeConfigService.getPlatformFeeConfigListByPlatformId(AMAZON_PLATFORM_ID);
            overview.put("feeConfigCount", feeConfigs.size());
            overview.put("enabledFeeCount", feeConfigs.stream().mapToInt(c -> Integer.valueOf(0).equals(c.getStatus()) ? 1 : 0).sum());
            
            // 同步配置
            Map<String, Object> syncConfig = getSyncConfig();
            overview.put("syncConfig", syncConfig);
            
            // 功能特性
            Map<String, Object> features = amazonPlatformConfig.getFeatures();
            overview.put("features", features);
            
            overview.put("lastUpdated", LocalDateTime.now());
            
        } catch (Exception e) {
            log.error("获取Amazon配置概览失败", e);
            overview.put("error", e.getMessage());
        }
        
        return overview;
    }

    // ==================== 私有方法 ====================

    /**
     * 初始化平台基础配置
     */
    private void initializePlatformConfig() {
        try {
            PlatformConfigDO existingConfig = platformConfigService.getPlatformConfigByCode(AMAZON_PLATFORM_CODE);
            if (existingConfig == null) {
                log.info("创建Amazon平台基础配置");
                createDefaultPlatformConfig();
            } else {
                log.info("Amazon平台基础配置已存在: {}", existingConfig.getId());
            }
        } catch (Exception e) {
            log.error("初始化Amazon平台基础配置失败", e);
        }
    }

    /**
     * 创建默认平台配置
     */
    private void createDefaultPlatformConfig() {
        try {
            PlatformConfigSaveReqVO configReqVO = new PlatformConfigSaveReqVO();
            configReqVO.setCode(AMAZON_PLATFORM_CODE);
            configReqVO.setName(AMAZON_PLATFORM_NAME);
            configReqVO.setType(1);
            configReqVO.setApiBaseUrl("https://sellingpartnerapi-na.amazon.com");
            configReqVO.setAuthType(2); // OAuth2
            configReqVO.setEnabled(true);
            configReqVO.setStatus(1); // 正常
            configReqVO.setSort(1); // 设置排序值

            // 设置默认配置
            configReqVO.setAuthConfig(createDefaultAuthConfig());
            configReqVO.setSyncConfig(createDefaultSyncConfig());
            configReqVO.setWebhookConfig(createDefaultWebhookConfig());
            configReqVO.setFeeConfig(createDefaultFeeConfig());
            configReqVO.setFeatures(createDefaultFeatures());
            configReqVO.setSupportedCurrencies("USD,EUR,GBP,JPY,CAD,AUD");
            configReqVO.setSupportedLanguages("en,es,fr,de,it,ja,zh");
            
            platformConfigService.createPlatformConfig(configReqVO);
            log.info("创建Amazon平台基础配置成功");
        } catch (Exception e) {
            log.error("创建Amazon平台基础配置失败", e);
        }
    }

    /**
     * 初始化API配置
     */
    private void initializeApiConfigs() {
        try {
            List<PlatformApiConfigDO> existingConfigs = platformApiConfigService.getPlatformApiConfigListByPlatformId(AMAZON_PLATFORM_ID);
            if (existingConfigs.isEmpty()) {
                log.info("创建Amazon API配置");
                createDefaultApiConfigs();
            } else {
                log.info("Amazon API配置已存在，数量: {}", existingConfigs.size());
            }
        } catch (Exception e) {
            log.error("初始化Amazon API配置失败", e);
        }
    }

    /**
     * 初始化费率配置
     */
    private void initializeFeeConfigs() {
        try {
            List<PlatformFeeConfigDO> existingConfigs = platformFeeConfigService.getPlatformFeeConfigListByPlatformId(AMAZON_PLATFORM_ID);
            if (existingConfigs.isEmpty()) {
                log.info("创建Amazon费率配置");
                createDefaultFeeConfigs();
            } else {
                log.info("Amazon费率配置已存在，数量: {}", existingConfigs.size());
            }
        } catch (Exception e) {
            log.error("初始化Amazon费率配置失败", e);
        }
    }

    /**
     * 创建默认API配置
     */
    private void createDefaultApiConfigs() {
        try {
            // 订单API配置
            Map<String, Object> ordersHeaders = new HashMap<>();
            ordersHeaders.put("Content-Type", "application/json");
            Map<String, Object> ordersParams = new HashMap<>();
            ordersParams.put("MarketplaceIds", "ATVPDKIKX0DER");
            ordersParams.put("MaxResultsPerPage", "50");
            Map<String, Object> ordersMapping = new HashMap<>();
            ordersMapping.put("Orders", "orders");
            ordersMapping.put("NextToken", "nextToken");
            createApiConfig("ORDERS", "Amazon Orders API", "/orders/v0/orders", "GET",
                ordersHeaders, ordersParams, ordersMapping, 10, 30000);

            // 商品API配置
            Map<String, Object> catalogHeaders = new HashMap<>();
            catalogHeaders.put("Content-Type", "application/json");
            Map<String, Object> catalogParams = new HashMap<>();
            catalogParams.put("MarketplaceId", "ATVPDKIKX0DER");
            catalogParams.put("Query", "*");
            Map<String, Object> catalogMapping = new HashMap<>();
            catalogMapping.put("Items", "products");
            catalogMapping.put("NextToken", "nextToken");
            createApiConfig("CATALOG", "Amazon Catalog API", "/catalog/v0/items", "GET",
                catalogHeaders, catalogParams, catalogMapping, 5, 30000);

            // 库存API配置
            Map<String, Object> inventoryHeaders = new HashMap<>();
            inventoryHeaders.put("Content-Type", "application/json");
            Map<String, Object> inventoryParams = new HashMap<>();
            inventoryParams.put("MarketplaceIds", "ATVPDKIKX0DER");
            inventoryParams.put("details", "true");
            Map<String, Object> inventoryMapping = new HashMap<>();
            inventoryMapping.put("InventorySummaries", "inventory");
            inventoryMapping.put("NextToken", "nextToken");
            createApiConfig("INVENTORY", "Amazon Inventory API", "/fba/inventory/v1/summaries", "GET",
                inventoryHeaders, inventoryParams, inventoryMapping, 30, 30000);

            // 报告API配置
            Map<String, Object> reportsHeaders = new HashMap<>();
            reportsHeaders.put("Content-Type", "application/json");
            Map<String, Object> reportsParams = new HashMap<>();
            reportsParams.put("reportTypes", "GET_MERCHANT_LISTINGS_ALL_DATA");
            Map<String, Object> reportsMapping = new HashMap<>();
            reportsMapping.put("reports", "reports");
            reportsMapping.put("NextToken", "nextToken");
            createApiConfig("REPORTS", "Amazon Reports API", "/reports/2021-06-30/reports", "GET",
                reportsHeaders, reportsParams, reportsMapping, 1, 60000);

            log.info("创建Amazon API配置成功");
        } catch (Exception e) {
            log.error("创建Amazon API配置失败", e);
        }
    }

    /**
     * 创建单个API配置
     */
    private void createApiConfig(String apiType, String apiName, String endpoint, String method,
                                Map<String, Object> headers, Map<String, Object> params,
                                Map<String, Object> mapping, Integer tps, Integer timeout) {
        try {
            PlatformApiConfigSaveReqVO configReqVO = new PlatformApiConfigSaveReqVO();
            configReqVO.setPlatformId(AMAZON_PLATFORM_ID);
            configReqVO.setApiType(apiType);
            configReqVO.setApiName(apiName);
            configReqVO.setApiEndpoint(endpoint);
            configReqVO.setHttpMethod(method);
            configReqVO.setRequestHeaders(toJsonString(headers));
            configReqVO.setRequestParams(toJsonString(params));
            configReqVO.setResponseMapping(toJsonString(mapping));
//            configReqVO.setRateLimitTps(tps);
            configReqVO.setTimeoutSeconds(timeout);
            configReqVO.setRetryTimes(3); // 设置默认重试次数
            configReqVO.setRetryIntervalSeconds(5); // 设置默认重试间隔（秒）
            configReqVO.setEnabled(true);
            configReqVO.setStatus(1);

            platformApiConfigService.createPlatformApiConfig(configReqVO);
        } catch (Exception e) {
            log.error("创建API配置失败: apiType={}", apiType, e);
        }
    }

    /**
     * 创建默认费率配置
     */
    private void createDefaultFeeConfigs() {
        try {
            // 推荐费率
            createFeeConfig("REFERRAL_FEE", "推荐费率", "Referral Fee", 1,
                new BigDecimal("0.15"), null, new BigDecimal("0.30"), null, "USD");

            // 履约费率
            createFeeConfig("FULFILLMENT_FEE", "履约费率", "Fulfillment Fee", 2,
                null, new BigDecimal("2.50"), new BigDecimal("1.00"), new BigDecimal("10.00"), "USD");

            // 存储费率
            createFeeConfig("STORAGE_FEE", "存储费率", "Storage Fee", 1,
                new BigDecimal("0.75"), null, new BigDecimal("0.10"), null, "USD");

            // 长期存储费率
            createFeeConfig("LONG_TERM_STORAGE_FEE", "长期存储费率", "Long-term Storage Fee", 2,
                null, new BigDecimal("6.90"), new BigDecimal("1.00"), null, "USD");

            // 退货处理费率
            createFeeConfig("RETURN_PROCESSING_FEE", "退货处理费率", "Return Processing Fee", 1,
                new BigDecimal("0.20"), null, new BigDecimal("0.50"), new BigDecimal("5.00"), "USD");

            log.info("创建Amazon费率配置成功");
        } catch (Exception e) {
            log.error("创建Amazon费率配置失败", e);
        }
    }

    /**
     * 创建单个费率配置
     */
    private void createFeeConfig(String feeType, String feeName, String feeNameEn, Integer calculationMethod,
                                BigDecimal feeRate, BigDecimal fixedAmount, BigDecimal minFee,
                                BigDecimal maxFee, String currency) {
        try {
            PlatformFeeConfigSaveReqVO configReqVO = new PlatformFeeConfigSaveReqVO();
            configReqVO.setPlatformId(AMAZON_PLATFORM_ID);
            configReqVO.setFeeType(feeType);
            configReqVO.setFeeName(feeName);
            configReqVO.setFeeNameEn(feeNameEn);
            configReqVO.setCalculationMethod(calculationMethod);
            configReqVO.setFeeRate(feeRate);
            configReqVO.setFixedAmount(fixedAmount);
            configReqVO.setMinFee(minFee);
            configReqVO.setMaxFee(maxFee);
            configReqVO.setCurrency(currency);
            configReqVO.setStatus(1);

            platformFeeConfigService.createPlatformFeeConfig(configReqVO);
        } catch (Exception e) {
            log.error("创建费率配置失败: feeType={}", feeType, e);
        }
    }

    /**
     * 创建默认授权配置
     */
    private String createDefaultAuthConfig() {
        Map<String, Object> authConfig = new HashMap<>();
        authConfig.put("clientId", "${amazon.auth.client-id}");
        authConfig.put("clientSecret", "${amazon.auth.client-secret}");
        authConfig.put("redirectUri", "${amazon.auth.redirect-uri}");
        authConfig.put("scope", "sellingpartnerapi::notifications");
        authConfig.put("authUrl", "https://sellercentral.amazon.com/apps/authorize/consent");
        authConfig.put("tokenUrl", "https://api.amazon.com/auth/o2/token");
        return toJsonString(authConfig);
    }

    /**
     * 创建默认同步配置
     */
    private String createDefaultSyncConfig() {
        Map<String, Object> syncConfig = new HashMap<>();
        syncConfig.put("orderSyncInterval", 30); // 订单同步间隔（分钟）
        syncConfig.put("productSyncInterval", 60); // 商品同步间隔（分钟）
        syncConfig.put("inventorySyncInterval", 15); // 库存同步间隔（分钟）
        syncConfig.put("batchSize", 50); // 批次大小
        syncConfig.put("maxRetryCount", 3); // 最大重试次数
        syncConfig.put("autoSync", true); // 是否自动同步
        syncConfig.put("syncTimeRange", 24); // 同步时间范围（小时）
        return toJsonString(syncConfig);
    }

    /**
     * 创建默认Webhook配置
     */
    private String createDefaultWebhookConfig() {
        Map<String, Object> webhookConfig = new HashMap<>();
        webhookConfig.put("enabled", true);
        webhookConfig.put("secretKey", "${amazon.webhook.secret-key}");
        webhookConfig.put("topicArn", "${amazon.webhook.topic-arn}");
        webhookConfig.put("eventTypes", Arrays.asList("ORDER_STATUS_CHANGE", "INVENTORY_UPDATE", "PRODUCT_UPDATE"));
        webhookConfig.put("retryCount", 3);
        webhookConfig.put("retryInterval", 60); // 重试间隔（秒）
        return toJsonString(webhookConfig);
    }

    /**
     * 创建默认费率配置
     */
    private String createDefaultFeeConfig() {
        Map<String, Object> feeConfig = new HashMap<>();
        feeConfig.put("defaultCurrency", "USD");
        feeConfig.put("feeCalculationMode", "AUTOMATIC");
        feeConfig.put("includeVAT", false);
        feeConfig.put("roundingMode", "HALF_UP");
        feeConfig.put("decimalPlaces", 2);
        return toJsonString(feeConfig);
    }

    /**
     * 创建默认功能特性
     */
    private String createDefaultFeatures() {
        Map<String, Object> features = new HashMap<>();
        features.put("orderSync", true); // 订单同步
        features.put("productSync", true); // 商品同步
        features.put("inventorySync", true); // 库存同步
        features.put("priceSync", true); // 价格同步
        features.put("webhookSupport", true); // Webhook支持
        features.put("bulkOperations", true); // 批量操作
        features.put("realTimeSync", false); // 实时同步
        features.put("advancedReporting", true); // 高级报告
        features.put("multiRegionSupport", true); // 多区域支持
        features.put("fbaSupport", true); // FBA支持
        return toJsonString(features);
    }

    /**
     * 解析JSON配置
     */
    private Map<String, Object> parseJsonConfig(String jsonStr) {
        if (jsonStr == null || jsonStr.trim().isEmpty()) {
            return new HashMap<>();
        }

        try {
            return objectMapper.readValue(jsonStr, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            log.warn("解析JSON配置失败: {}", jsonStr, e);
            return new HashMap<>();
        }
    }

    /**
     * 转换为JSON字符串
     */
    private String toJsonString(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("转换JSON字符串失败", e);
            return "{}";
        }
    }
}
